<?php
namespace Service;

class ApiLimit extends Base
{

    //redis键的前缀
    private $prefix = 'api_limit';

    //redis实例
    private $redis = null;

    //redis键的一部分
    private $key = '';

    //时间粒度
    private $per = 1;

    //每分钟能够访问的次数
    private $total = 1;

    //redis键的过期时间
    private $time = 60;

    public function init()
    {
        $redis = $this->get(CACHE_APILIMIT)->getRedis();
        return $this->setRedis($redis);
    }

    //当天的第几秒
    private function getTodaySecond()
    {
        $yestoday = date('Y-m-d 23:59:59', strtotime('-1 day'));
        return time() - strtotime($yestoday);
    }

    public function setRedis($redis)
    {
        $this->redis = $redis;
        return $this;
    }

    private function setExpire($key)
    {
        if($this->redis->ttl($key) == -1){
            $this->redis->expire($key, $this->time);
        }
    }

    public function setKey($key)
    {
        $this->key = $key;
        return $this;
    }

    private function getKey()
    {
        $per = $this->per;
        $i = $this->getTodaySecond();
        $index = ceil($i / $this->per);
        return "{$this->prefix}_{$per}_{$index}_{$this->key}";
    }

    //时间粒度,多少秒为一个统计单位
    public function setPer($per = 1)
    {
        $this->per = $per;
        return $this;
    }

    public function setTotal($total = 1)
    {
        $this->total = $total;
        return $this;
    }

    public function setTime($time = 60)
    {
        $this->time = $time;
        return $this;
    }

    //如果返回true，表示还没有超过限制的次数
    public function check()
    {
        $key = $this->getKey();
        $total = (int)$this->redis->get($key);
        return ($total < $this->total);
    }

    public function add()
    {
        $key = $this->getKey();
        $this->redis->incrBy($key, 1);
        $this->setExpire($key);
    }

}